﻿using System;
using System.Collections.Generic;
using System.Net;


namespace ET
{
	[MessageHandler]
	public class C2R_LoginHandler : AMRpcHandler<C2R_Login, R2C_Login>
	{
		protected override async ETTask Run(Session session, C2R_Login request, R2C_Login response, Action reply)
		{
			try
			{
				DBComponent db = session.DomainScene().GetComponent<DBComponent>();
				List<TAccount> result = await db.Query<TAccount>(x => x.Account == request.Account);
				//验证账号是否存在
				if(result.Count < 1)
                {
					response.Error = ErrorCode.ERR_Error;
					response.Message = "账号不存在";
					reply();
					return;
                }

				TAccount account = result[0];
				//验证密码是否正确
				if(account.Password != request.Password)
                {
					response.Error = ErrorCode.ERR_Error;
					response.Message = "密码错误";
					reply();
					return;
				}
				
				

				// 随机分配一个Gate
				StartSceneConfig config = RealmGateAddressHelper.GetGate(session.DomainZone());

				// 向gate请求一个key,客户端可以拿着这个key连接gate
				G2R_GetLoginKey g2RGetLoginKey = (G2R_GetLoginKey)await ActorMessageSenderComponent.Instance.Call(
					config.SceneId, new R2G_GetLoginKey() { Account = request.Account });

				response.Address = config.OuterIPPort.ToString();
				response.Error = ErrorCode.ERR_Success;
				response.Key = g2RGetLoginKey.Key;
				response.GateId = g2RGetLoginKey.GateId;
				response.UserId = account.Id;
				reply();
			}
			catch(Exception e)
            {
				ReplyError(response, e, reply);
            }
		}
	}
}